package org.wings27.utils;

import org.mozilla.universalchardet.UniversalDetector;

import java.io.IOException;
import java.io.InputStream;

/**
 * Project Name: answerIt
 * Date Created: 2013/11/21 19:09
 *
 * @author wings
 */
public class EncodingDetector {

    public static final int DEFAULT_READ_LENGTH = 4096;
    private int readLength;

    public EncodingDetector() {
        this(DEFAULT_READ_LENGTH);
    }

    public EncodingDetector(int readLength) {
        this.readLength = readLength;
    }

    public String detect(InputStream fileInputStream) throws IOException {
        UniversalDetector detector = new UniversalDetector(null);
        int readLength;
        byte[] buf = new byte[this.readLength];
        while ((readLength = fileInputStream.read(buf)) > 0 && !detector.isDone()) {
            detector.handleData(buf, 0, readLength);
        }

        detector.dataEnd();
        String encoding = detector.getDetectedCharset();
        detector.reset();
        return encoding;
    }
}
